package database;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by jimmyhsu on 2016/12/2.
 */
public class TakeCourseDb {
    private static DatabaseBasic mSqlHelper;

    public static void addCourseForStudent(String studentId, int courseId) {
        String sql = "insert into takecourse (studentId, courseId) values (\'"+ studentId + "\', " + courseId + ")";
        execSqlUpdate(sql);
    }

    private static void execSql(String sql) {
        mSqlHelper = new DatabaseBasic();
        mSqlHelper.executeSql(sql);
        mSqlHelper.recycle();
    }

    private static void execSqlUpdate(String sql) {
        mSqlHelper = new DatabaseBasic();
        mSqlHelper.executeSqlUpdate(sql);
        mSqlHelper.recycle();
    }

    public static void removeStudentFromCourse(String studentId, int courseId) {
        String sql = "delete from takecourse where studentId = \'" + studentId + "\' and courseId = " + courseId;
        execSqlUpdate(sql);
    }

    public static boolean studentAlreadyInCourse(String studentId, int courseId) {
        String sql = "select count(*) from takecourse where studentId=\'" + studentId + "\' and courseId=" + courseId;
        mSqlHelper = new DatabaseBasic();
        ResultSet resultSet = mSqlHelper.executeSql(sql);
        try {
            if (resultSet.next()) {
                return resultSet.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            mSqlHelper.recycle();
        }
        return false;
    }

}
